<template>
  <div class="tab-bar">
    <van-tabbar v-model="currentIndex" active-color="#ff9854">
      <template v-for="(item, index) in tabbarData">
        <van-tabbar-item @click="handleItemClick(item)">
          <template #default>
            <span>{{ item.text }}</span>
          </template>
          <template #icon>
            <img v-if="currentIndex !== index" :src="getAssetURL(item.image)" alt="" />
            <img v-else :src="getAssetURL(item.imageActive)" alt="" />
          </template>
        </van-tabbar-item>
      </template>
    </van-tabbar>
  </div>
</template>

<script setup>
import tabbarData from '@/assets/data/tabbar';
import { useRoute, useRouter } from 'vue-router'
// 动态加载图片
import { getAssetURL } from '@/utils/load_assets'
import { ref, watch } from 'vue';
import useUserStore from '@/stores/modules/user';
import { showToast } from 'vant';

// 监听路由改变时，找到对应的索引，设置currentIndex
const route = useRoute()
const router = useRouter()
const userStore = useUserStore()
const currentIndex = ref(0)

// 定义需要登录的路径
const authPaths = ['/favor', '/order', '/message']

watch(route, (newRoute) => {
  const index = tabbarData.findIndex(item => item.path === newRoute.path)
  if (index === -1) return
  currentIndex.value = index
})

// 处理点击事件
const handleItemClick = (item) => {
  // 检查是否需要登录权限的路径
  if (authPaths.includes(item.path)) {
    // 检查用户是否已登录
    if (!userStore.isLoggedIn()) {
      showToast({
        type: 'fail',
        message: '请先登录',
        duration: 1500
      })
      // 跳转到登录页面，并携带重定向信息
      router.push({
        path: '/login',
        query: { redirect: item.path }
      })
      return
    }
  }

  // 用户已登录或不需要权限，正常跳转
  router.push(item.path)
}
</script>

<style lang="less" scoped>
.tab-bar {
  img {
    height: 24px;
  }
}
</style>
